﻿using System;
using System.Collections.Generic;
using System.Xml.Linq;
using LinqToLfsWorld.Extensions;

namespace LinqToLfsWorld.Queries
{
	/// <summary>
	/// Queries LfsWorld for racer fuel information.
	/// </summary>
	public class RacerFuelQuery : LfsWorldQuery<RacerFuel>
	{

		/// <summary>
		/// Initializes a new instance of the <see cref="RacerFuelQuery"/> class.
		/// </summary>
		/// <param name="context">The context.</param>
		public RacerFuelQuery(LfsWorldContext context)
			: base(context)
		{
		}

		/// <summary>
		/// Gets the URL used to query LfsWorld.
		/// </summary>
		protected override string GetUrl()
		{
			string url = LfsHelper.GetPubstatUrlBase(PubstatResponseType.Xml, this, "fuel");

			url += "&racer=" + (string)ExpressionValues["RacerName"].Value;

			return url;
		}

		/// <summary>
		/// Gets the entities given LfsWorld response XML
		/// </summary>
		/// <param name="responseData">The response data.</param>
		/// <returns>A collection of Host entities</returns>
		protected override IEnumerable<RacerFuel> ProcessResponse(string responseData)
		{

			XDocument doc = XDocument.Parse(responseData);

			foreach (var node in doc.Descendants("entry"))
			{
				RacerFuel fuel = new RacerFuel();

				fuel.RacerName = ((string)ExpressionValues["RacerName"].Value).StripLfsColours();
				fuel.FuelPercentage = Convert.ToSingle(node.Element("fuel").Value);
				fuel.TrackIdent = node.Element("track").Value;
				fuel.TrackName = Utility.CircuitNameFactory.GetNameFromIdent(fuel.TrackIdent);
				fuel.Car = node.Element("car").Value;

				yield return fuel;
			}

		}
	}
}
